#!/usr/bin/ruby

require 'net/http'
require 'uri'
require 'kconv'

Net::HTTP.version_1_2

module WebService
  class Simple
    def initialize
      @params = {}
      @user_agent = "Ruby/#{RUBY_VERSION}"

      options = {}
      options = @@instance_values[self.class.to_s]  if @@instance_values.key?(self.class.to_s)

      options.each_pair do |k, v|
        send(k, *v)
      end
    end

    def base_url(url)
      @base_url = URI.parse(url)
    end

    def basic_auth(username, password)
      @username = username
      @password = password
    end

    def params(p)
      @params = p
    end

    def user_agent(ua = nil)
      if ua.nil?
        @user_agent
      else
        @user_agent = ua
      end
    end

    def post(request_uri, params = {})
      p = @params.merge(params)

      Net::HTTP.start(@base_url.host, @base_url.port) do |http|
        req = Net::HTTP::Post.new(@base_url.request_uri + request_uri)
        req["user-agent"] = @user_agent  unless @user_agent.empty?

        req.basic_auth(@username, @password)  if @username && @password
        req.set_form_data(p)

        res = http.request(req)

        res.body.toutf8
      end
    end

    def get(request_uri, params = {})
      p = params.map{|key, value|
        "#{URI.encode(key)}=#{URI.encode(value)}"
      }.join("&")
      p = '?' + p  unless p.empty?

      Net::HTTP.start(@base_url.host, @base_url.port) do |http|
        req = Net::HTTP::Get.new(@base_url.request_uri + request_uri + p)
        req["user-agent"] = @user_agent  unless @user_agent.empty?

        req.basic_auth(@username, @password)  if @username && @password

        res = http.request(req)

        res.body.toutf8
      end
    end

    @@instance_values = {}
    METHODS = [:base_url, :basic_auth, :params, :user_agent]

    def self.method_missing(name, *args)
      # TODO: exception を発生させる
      return nil  unless METHODS.include?(name)

      c = self.to_s

      @@instance_values[c] = {}  unless @@instance_values.key?(c)

      @@instance_values[c][name] = args
    end
  end
end

